package com.krtech.wecard.module.mayi.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.krtech.wecard.framework.security.Inner;
import com.krtech.wecard.module.mayi.MayiPayEnums;
import com.krtech.wecard.module.mayi.entity.*;
import com.krtech.wecard.module.mayi.mapper.MayiPayListMapper;
import com.krtech.wecard.module.mayi.service.MayiPayListService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/mayiOrder")
@Slf4j
@Api(value = "蚂蚁阅读量后台订单管理")
public class MayiOrderController {

    @Autowired
    private MayiPayListService mayiPayListService;

    @Autowired
    private MayiPayListMapper payListMapper;

    @GetMapping("/list")
    @ApiOperation(value = "list")
    public List<MayiPayList> list(String startTime, String endTime, Integer status, String phone) {
        QueryWrapper<MayiPayList> wrapper = new QueryWrapper<>();
        if (StrUtil.isNotEmpty(startTime) && StrUtil.isNotEmpty(endTime)){
            wrapper.between(MayiPayList.COL_CREATED_TIME,startTime,endTime);
        }

        if (status != null){
            wrapper.eq(MayiPayList.COL_STATUS,status);
        }

        if (StrUtil.isNotEmpty(phone)){
            wrapper.eq(MayiPayList.COL_FK_USER_CODE,phone);
        }

        wrapper.orderByDesc(MayiPayList.COL_CREATED_TIME);

        List<MayiPayList> list = mayiPayListService.list(wrapper);
        return list;
    }

    @GetMapping("/deleteById")
    @ApiOperation(value = "deleteById")
    public boolean page(Integer id){
        return mayiPayListService.removeById(id);
    }

    /**
     *
     * @param page
     * @param startTime
     * @param endTime
     * @param status
     * @param phone
     * @param url
     * @param cdkCode
     * @param orderNo
     * @param type:任务类型，1：阅读量，2：点赞，3：评论
     * @return
     */
    @GetMapping("/page")
    @ApiOperation(value = "page")
    public Page<MayiPayListVo> page(Page<MayiPayList> page,String startTime, String endTime, Integer status, String phone,String url,String cdkCode,String orderNo,String type) {
        //todo 修正时区
        QueryWrapper<MayiPayList> wrapper = new QueryWrapper<>();
        if (StrUtil.isNotEmpty(url)){
            if (url.contains("&")){
                String reviewUrl = url.substring(0,url.indexOf("&"));
                wrapper.and(i->{
                    i.like(MayiPayList.COL_URL,reviewUrl);
                });
            }else {
                wrapper.and(i->{
                    i.like(MayiPayList.COL_URL,url);
                });
            }
        }

        if (StrUtil.isNotEmpty(type)){
            wrapper.and(i->{
                i.like(MayiPayList.COL_TYPE,type);
            });
        }

        if (StrUtil.isNotEmpty(cdkCode)){
            wrapper.and(i->{
                i.like(MayiPayList.COL_CDK_CODE,cdkCode);
            });
        }

        if (StrUtil.isNotEmpty(orderNo)){
            wrapper.and(i->{
                i.like(MayiPayList.COL_ORDER_NO,orderNo);
            });
        }

        if (StrUtil.isNotEmpty(startTime) && StrUtil.isNotEmpty(endTime)){
            wrapper.between(MayiPayList.COL_CREATED_TIME,startTime,endTime);
        }

        if (status != null){
            wrapper.eq(MayiPayList.COL_STATUS,status);
        }

        if (StrUtil.isNotEmpty(phone)){
            wrapper.eq(MayiPayList.COL_FK_USER_CODE,phone);
        }

        wrapper.orderByDesc(MayiPayList.COL_CREATED_TIME);

        Page<MayiPayList> payListPage = mayiPayListService.page(page, wrapper);

        //增加该任务服务 机器的数量
        List<ServcieMachineCount> serviceMachineCount = payListMapper.getServiceMachineCount();

        List<MayiPayListVo> payListVoList = payListPage.getRecords().stream().map(mayiPayList -> {
            MayiPayListVo payListVo = new MayiPayListVo();
            BeanUtil.copyProperties(mayiPayList, payListVo);

            List<ServcieMachineCount> machineCountList = serviceMachineCount.stream().filter(servcieMachineCount -> {
                return servcieMachineCount.getFkOrderNo().equals(payListVo.getOrderNo());
            }).collect(Collectors.toList());

            if (machineCountList.size() > 0) {
                ServcieMachineCount machineCount = machineCountList.get(0);
                payListVo.setMachineCount(machineCount.getMachineCount());
            } else {
                payListVo.setMachineCount(0);
            }
            return payListVo;
        }).collect(Collectors.toList());

        Page<MayiPayListVo> voPage = new Page<>();
        BeanUtil.copyProperties(payListPage,voPage);
        voPage.setRecords(payListVoList);


        return voPage;
    }

    //
    @GetMapping("/statistics")
    @ApiOperation(value = "statistics")
    public List<StatisticsVo> statistics(String startTime, String endTime, Integer status, String phone) {
        List<StatisticsVo> statisticsVoList = new ArrayList<StatisticsVo>();

        //获得偏移量
        long allOffset = DateUtil.betweenDay(DateUtil.parseDate(startTime), DateUtil.parseDate(endTime), true);

        for (int offset = 0;offset <= allOffset;offset++){
            //用startTime开始偏移
            DateTime dayStart = DateUtil.offsetDay(DateUtil.parseDate(startTime), offset);
            String querysStart = DateUtil.formatDateTime(dayStart);
            DateTime dayEnd = dayStart.offset(DateField.SECOND, 86399);
            String querysEnd = DateUtil.formatDateTime(dayEnd);
            //获得今天的统计数据
            StatisticsQueryVo queryVo = new StatisticsQueryVo();
            queryVo.setStartTime(querysStart);
            queryVo.setEndTime(querysEnd);
            queryVo.setStatus(status);
            queryVo.setPhone(phone);

            //获得一天的量
            Integer daySum = payListMapper.queryStatistics(queryVo);

            //年月日
            StatisticsVo statisticsVo = new StatisticsVo();
            statisticsVo.setDay(dayStart);
            statisticsVo.setDaySum(daySum);

            statisticsVoList.add(statisticsVo);
        }

        return statisticsVoList;
    }

    @GetMapping("/statisticsDianzan")
    @ApiOperation(value = "statisticsDianzan")
    public List<StatisticsVo> statisticsDianzan(String startTime, String endTime, Integer status, String phone) {
        List<StatisticsVo> statisticsVoList = new ArrayList<StatisticsVo>();

        //获得偏移量
        long allOffset = DateUtil.betweenDay(DateUtil.parseDate(startTime), DateUtil.parseDate(endTime), true);

        for (int offset = 0;offset <= allOffset;offset++){
            //用startTime开始偏移
            DateTime dayStart = DateUtil.offsetDay(DateUtil.parseDate(startTime), offset);
            String querysStart = DateUtil.formatDateTime(dayStart);
            DateTime dayEnd = dayStart.offset(DateField.SECOND, 86399);
            String querysEnd = DateUtil.formatDateTime(dayEnd);
            //获得今天的统计数据
            StatisticsQueryVo queryVo = new StatisticsQueryVo();
            queryVo.setStartTime(querysStart);
            queryVo.setEndTime(querysEnd);
            queryVo.setStatus(status);
            queryVo.setPhone(phone);

            //获得一天的量
            Integer daySum = payListMapper.statisticsDianzan(queryVo);

            //年月日
            StatisticsVo statisticsVo = new StatisticsVo();
            statisticsVo.setDay(dayStart);
            statisticsVo.setDaySum(daySum);

            statisticsVoList.add(statisticsVo);
        }

        return statisticsVoList;
    }
}
